<template>
	<view class="_abbr">
		<view class="public">
			<view class="scan-item" style="display: flex; border: 1px solid #eee;">
				<input
					:focus="isFocus" 
					placeholder="扫描或输入二维码" 
					:value="requestParams.deviceQr" 
					@blur="confirm" 
					type="text" 
					class="input">
				<view class="right-icon">
					<view class="icon" @click="doScan1">
						<u-icon size="30" name="scan"></u-icon>
					</view>
				</view>
			</view>
		</view>
		<view class="public">
			<view class="main_body_view main_body_view_view" >
				设备检测人：{{testUserList || ''}}
			</view>
			<view class="main_body_view main_body_view_view">
				设备验机人：{{ testMachineList || ''}}
			</view>
			<view class="main_body_view main_body_view_view">
				设备类型：{{dataForm.deviceType || ''}}
			</view>
			<view class="main_body_view main_body_view_view">
				设备品牌：{{dataForm.deviceBrand || ''}}
			</view>
			<view class="main_body_view main_body_view_view">
				设备型号：{{dataForm.deviceModel || ''}}
			</view>
			<view class="main_body_view main_body_view_view">
				设备规格：{{deviceSpecs1 || ''}}
			</view>
			<view class="main_body_view main_body_view_view">
				<view style="font-weight: 700;">需要验机的问题：</view>
				<view v-for="(item, index) in testDetail" :key="item.id">
					<view :style="{ color: (item.faultFromTest === 2) ? 'dodgerblue' : 'black' }">{{item.faultType}}</view>
				</view>
			</view>
			<view>
				<u-button type="primary" @click="updateDevice">修改当前设备型号</u-button>
			</view>
		</view>
		<view class="public">
			<!-- <div style="display: flex;">
				<u-button @click="addFaultDevice">+请添加故障类型+</u-button>
			</div>
			<u-row gutter="12" justify="space-between">
				<u-col span="4" textAlign="center" align="center">故障类型</u-col>
				<u-col span="4" textAlign="center" align="center">故障来源</u-col>
				<u-col span="4" textAlign="center" align="center">故障是否修复</u-col>
			</u-row>
			<view v-for="(item,index) in addDoubleDeviceForm.items" :key="index" style="margin: 20rpx 0;font-size: 14px">
				<u-row gutter="12">
					<u-col span="4" textAlign="center" align="center">{{item.faultType}}</u-col>
					<u-col span="4" textAlign="center" align="center">{{testChange(item.faultFromTest)}}</u-col>
					<u-col span="4" textAlign="center" align="center">{{fixedChange(item.faultFixed)}}</u-col>
				</u-row>
			</view>
			<pickerSearch v-model="showFaultOpen" :dataSource='doubleDevice' :pickerValues="[0]" @recload='confirmDoubleDevice'></pickerSearch> -->
			<view style="font-weight: 600;padding-bottom: 5px;">故障信息：</view>
			<view class="device-fault">
				<view class="fault-item">
					<view v-for="(group, faultPart) in deviceFaultList" :key="faultPart">
					  <h2>{{ faultPart }}</h2>
					  <u-checkbox-group
					  	placement="column"
					  >
					  	<u-checkbox
					  		:customStyle="{marginBottom: '8px'}"
					  		v-for="item in group"
					  		:key="item.id"
					  		:label="item.deviceFaultType"
					  		:name="item.deviceFaultType"
					  		:checked="item.checked"
					  		@change="handleFaultChange(item)"
					  	>
					  	</u-checkbox>
					  </u-checkbox-group>
					</view>
				</view>
			</view>
			<view class="button" style="margin-top: 40rpx;">
				<u-button type="primary" text="提交故障类型" @click="addTypebtn"></u-button>
				<!-- <u-button type="primary" text="新增故障类型" @click="handleAddType"></u-button> -->
			</view>
			<u-modal
				:show="show" 
				title="新增复检故障类型" 
				@confirm="addFaultType" 
				@cancel="handleCancel" 
				show-cancul-button
				mask-close-able>
				<view>
					<u-form :model="faultForm" ref="uForm">
						<u-form-item label="故障类型">
							<u-input v-model="faultForm.faultType" placeholder="请输入故障类型"/>
						</u-form-item>
					</u-form>
				</view>
			</u-modal>
		</view>
		<view class="public">
			<view style="font-weight: 600;padding-bottom: 5px;">请勾选已修复的问题：</view>
			<u-row gutter="12" justify="center">
				<u-col span="6" textAlign="center" align="center">故障类型</u-col>
				<u-col span="3" textAlign="center" align="center">故障来源</u-col>
				<u-col span="3" textAlign="center" align="center">是否修复</u-col>
			</u-row>
			<view v-for="(item, index) in doubleDeviceForm.items" :key="item.id" style="margin: 20rpx 0;font-size: 14px">
				<u-row gutter="12" justify="center" align="center">
					<u-col span="6" textAlign="center" align="center">{{item.faultType}}</u-col>
					<u-col span="4" textAlign="center" align="center">
						{{testChange(item.faultFromTest)}}
					</u-col>
					<u-col span="2" textAlign="center" align="center">
						<u-checkbox-group>
							<u-checkbox v-model="item.faultFixed" :checked="item.faultFixed" @change="handleFaultFixedChange(item)"></u-checkbox>
						</u-checkbox-group>
					</u-col>
				</u-row>
			</view>
			<u-picker :show="showSelectFaultFixed" :columns="columns" @confirm="handleConfirmSelect"></u-picker>
			<view class="button" style="margin-top: 40rpx;">
				<u-button type="primary" text="修改验机故障" @click="subFaultType"></u-button>
			</view>
		</view>
		<view class="public">
			<view class="button">
				<u-button type="primary" @click="sub" text="提交工单" :disabled="buttonDisabled"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '@/utils/request';
	import {debounce} from '@/utils/debounce.js'
	import pickerSearch from '@/compoments/pickerSearch.vue'
	export default {
		name: 'main',
		components: {pickerSearch},
		onLoad(options) {
			this.doubleDeviceForm.orderTestingId = options.orderTestingId
			this.addDoubleDeviceForm.orderTestingId = options.orderTestingId
			this.orderTestingId = options.orderTestingId
			uni.showLoading({
				title: "正在加载中"
			})
			this.BaseUrl = getApp().globalData.baseURL;
			this.getData(options.orderTestingId)
			uni.hideLoading()
		},
		onUnload() {
			uni.$off('q-sign') //移除监听事件
		},
		data() {
			return {
				deviceFaultList: [], //故障列表
				isFocus: true, // 二维码是否聚焦
				inputTimer: null, //定时器
				isFocus: true, // 是否聚焦
				showFaultOpen: false,
				orderTestingId: '',
				doubleDeviceForm: {
					orderTestingId: '',
					items: [],
				},
				addDoubleDeviceForm: {
					orderTestingId: '',
					items: [],
				},
				testUserList: '', // 检测人
				settleUserList: '', // 整备人
				testMachineList: '',  // 验机人
				afterSaleList: '', //售后人
				showSelectFaultFixed: false,
				columns: ['是', '否'],
				testDetail: [],
				faultForm: {},
				show:false,
				testingForm: {},
				// 基本案列数据
				doubleDevice: [], //复检故障类型
				buttonDisabled: false,
				proud: "",
				BaseUrl: "",
				dataForm: {}, // 数据工单
				historyList: [], //过程工单
				requestParams: {
					deviceQr: null
				}, // 扫码参数
				deviceSpecs1: null,
				subForm: {
					orderTestingId: "",
					method: "",
				}, //提交工单
				writeFlag: undefined,
			}
		},
		methods: {
			// 设备故障checkbox
			handleFaultChange(item) {
				item.checked= !item.checked
				// console.log(item)
				if (item.checked) {
					this.addDoubleDeviceForm.items.push({
						orderTestingId: this.orderTestingId,
						deviceQr: this.requestParams.deviceQr,
						faultType: item.deviceFaultType,
						faultFromTest: 1,
						faultFixed: false
					})
				}
			},
			// 修改设备
			updateDevice() {
				const workId = this.orderTestingId
				uni.navigateTo({
					url: 'selectedDevice?workId=' + workId
				});
			},
			// 获取选取返回的参数
			otherFun(item) {
				if (item) {
					if (this.dataForm) {
						request({
							url: 'system/detail',
							method: "PUT",
							data: {
								deviceQr: this.requestParams.deviceQr,
								workOrderId: this.dataForm.workOrderId,
								deviceSn: this.dataForm.deviceSn,
								deviceModelId: item.id
							}
						}).then(res => {
							this.getDeviceData()
							uni.showToast({
								title:"修改设备型号成功",
								icon:'none'
							})
						})
					} else {
						request({
							url: 'system/detail',
							method: "POST",
							data: {
								deviceQr: this.requestParams.deviceQr,
								workOrderId: this.orderTestingId,
								// deviceSn: this.dataForm ? this.dataForm.deviceSn || '' : '1',
								deviceModelId: item.id
							}
						}).then(res => {
							this.getDeviceData()
							uni.showToast({
								title:"修改设备型号成功",
								icon:'none'
							})
						})
					}
				}
			},
			testChange(statusId) {
				let text = "";
				switch (statusId) {
					case 0:
						text = "检测";
						break;
					case 1:
						text = "整备";
						break;
					case 2:
						text = "验机";
						break;
					case 3:
						text = "售后";
						break;
					default:
						text = '验机';
						break;
				}
				return text;
			},
			fixedChange(statusId) {
				let text = "";
				switch (statusId) {
					case true:
						text = "是";
						break;
					case false:
						text = "否";
						break;
					default:
						text = '未知';
						break;
				}
				return text;
			},
			// 二维码确定
			confirm(e) {
				this.isFocus = false
				this.requestParams.deviceQr = e.detail.value
				if (this.requestParams.deviceQr) {
					this.getDeviceData()
					this.getTestDetail()
				}
			},
			// 扫码id
			doScan1() {
				uni.scanCode({
					success: (res) =>{
						this.requestParams.deviceQr = res.result
						this.getDeviceData()
						this.getTestDetail()
					}
				})
			},
			// 修改故障类型
			subFaultType() {
				// console.log("12", this.doubleDeviceForm.items)
				request({
					url: 'system/doubleDevice/updateBatch',
					method: "PUT",
					data: this.doubleDeviceForm.items
				}).then(res => {
					if (res.code === 200) {
						uni.showToast({
							title: '修改整备故障成功',
						});
					}
					this.reset()
				})
			},
			// 新增故障类型
			addTypebtn() {
				request({
					url: 'system/doubleDevice/batchFault',
					method: "POST",
					data: this.addDoubleDeviceForm.items
				}).then(res => {
					uni.showToast({
						title: '提交故障类型成功',
					});
					this.getTestDetail()
					this.getDeviceFaultList(this.dataForm.deviceTypeId)
					this.addDoubleDeviceForm.items = []
				})
			},
			sub() {
				this.subForm.orderTestingId = this.orderTestingId
				this.subForm.method = "end_testorder"
				// 提交form
				request({
					url: 'system/testing',
					method: "PUT",
					data: this.subForm
				}).then(res => {
					uni.reLaunch({
						url: '/pages/view/recheck/index'
					})
				})
			},
			// 请求数据
			getData(workId) {
				request({
					method: "GET",
					url: `system/testing/${workId}`
				}).then(res => {
					this.testingForm = res.data;
				})
			},
			selectFaultFixed() {
				this.showSelectFaultFixed = true
			},
			handleConfirmSelect(data) {
				console.log("1", data)
			},
			changeTrue(item) {
				item.faultFixed = !item.faultFixed;
			},
			handleFaultFixedChange(item) {
				item.faultFixed = !item.faultFixed
				console.log("value", item.faultFixed)
			},
			// 添加故障设备
			addFaultDevice() {
				if (!this.requestParams.deviceQr) {
					uni.showToast({
						title:"请输入设备二维码",
						icon:'none'
					})
					return
				}
				this.showFaultOpen = true;
				this.getDoubleDevice()
			},
			// 确定添加设备
			confirmDoubleDevice(data) {
				// console.log(data, '选择的数据')
				this.addDoubleDeviceForm.items.push({
					orderTestingId: this.orderTestingId,
					deviceQr: this.requestParams.deviceQr,
					faultType: data.name,
					faultFromTest: 2,
					faultFixed: false
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.forEach((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, name) {
				return new Promise((resolve, reject) => {
					uni.$u.http.upload(`${this.BaseUrl}system/oss/upload`, {
						params: {},
						/* 会加在url上 */
						// #ifdef APP-PLUS || H5
						files: [], // 需要上传的文件列表。使用 files 时，filePath 和 name 不生效。App、H5（ 2.6.15+）
						// #endif
						filePath: url, // 要上传文件资源的路径。
						// 注：如果局部custom与全局custom有同名属性，则后面的属性会覆盖前面的属性，相当于Object.assign(全局，局部)
						custom: {
							auth: true
						}, // 可以加一些自定义参数，在拦截器等地方使用。比如这里我加了一个auth，可在拦截器里拿到，如果true就传token
						name: 'file', // 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
						// #ifdef H5 || APP-PLUS
						timeout: 60000, // H5(HBuilderX 2.9.9+)、APP(HBuilderX 2.9.9+)
						// #endif
						header: {
							Authorization: uni.getStorageSync("token")
						},
						/* 会与全局header合并，如有同名属性，局部覆盖全局 */
						formData: {}, // HTTP 请求中其他额外的 form data
						// 返回当前请求的task, options。请勿在此处修改options。非必填
						getTask: (task, options) => {},
					}).then((res) => {
						console.log(res);
						if (name == 1) {
							this.deviceImages.fileUrls.push(
								res.data.data.url.replace("blob:", ""),
							)
						}
						resolve(res.data.data.url)
						// 返回的res.data 已经进行JSON.parse
					}).catch(err => {

					})
				})
			},
			// 请求复检故障类型
			getDeviceFaultList(deviceTypeId) {
				request({
					url: "system/faultType/list",
					method:"GET",
					data: {
						deviceTypeId: deviceTypeId
					},
				}).then(res => {
					this.deviceFaultList = this.groupFaults(res.rows);
				})
			},
			groupFaults(faults) {
				const grouped = {};
				faults.forEach(fault => {
					if (!grouped[fault.faultPart]) {
						grouped[fault.faultPart] = [];
					}
					const faultWithChecked = { ...fault, checked: false }; // 添加 checked 属性并赋值为 false
					grouped[fault.faultPart].push(faultWithChecked);
				});
				return grouped;
			},
			// 选择设备数据
 			reset() {
				this.requestParams = {}
				this.dataForm = {}
				this.deviceSpecs1 = null
				this.testDetail = {}
				this.testUserList = ''
				this.settleUserList = ''
				this.testMachineList = ''
				this.afterSaleList = ''
				this.doubleDeviceForm = {
					orderTestingId: this.orderTestingId,
					items: []
				},
				this.addDoubleDeviceForm = {
					orderTestingId: this.orderTestingId,
					items: []
				}
			},
			// 设备详情数据
			debounceGetDevice: debounce(function() {
				if (this.requestParams.deviceQr.trim() !== '') {
					this.getDeviceData()
					this.getTestDetail()
				}
			}, 1000),
			// 获取单个设备详情
			getDeviceData() {
				this.deviceSpecs1 = ''
				request({
					method: "GET",
					url: `system/detail/${this.requestParams.deviceQr}`,
				}).then(res => {
					if (res.data && res.data.deviceSpecs) {
					    this.dataForm = res.data;
					    const specs1 = JSON.parse(res.data.deviceSpecs || "[]");
					    const formattedData = specs1.map(item => item[2]);
					    const resultString = formattedData.join('/');
					    this.deviceSpecs1 = resultString;
						this.getDeviceFaultList(res.data.deviceTypeId)
					    // this.deviceContent.name = `${res.data.deviceType}/${res.data.deviceBrand}/${res.data.deviceModel}${resultString}`;
					} else {
					    // 处理 deviceSpecs 为空的情况
					    this.dataForm = res.data;
						this.getDeviceFaultList(res.data.deviceTypeId)
					}
				})
			},
			// 获取检测的详情
			getTestDetail() {
				request({
					method: "GET",
					url: 'system/doubleDevice/list',
					data: {
						deviceQr: this.requestParams.deviceQr,
						// faultFixed: false
					}
				}).then(res => {
					this.testDetail = res.rows
					this.doubleDeviceForm.items = res.rows
					const deviceQrSet = new Set(res.rows.map(item => item.testUser));
					const deviceQrSet1 = new Set(res.rows.map(item => item.settleUser));
					const deviceQrSet2 = new Set(res.rows.map(item => item.afterUser));
					const deviceQrSet3 = new Set(res.rows.map(item => item.valUser));
					const deviceQrList = Array.from(deviceQrSet);
					const deviceQrList1 = Array.from(deviceQrSet1);
					const deviceQrList2 = Array.from(deviceQrSet2);
					const deviceQrList3 = Array.from(deviceQrSet3);
					this.testUserList = deviceQrList.join(', ');
					this.settleUserList = deviceQrList1.join(', ');
					this.afterSaleList = deviceQrList2.join(', ');
					this.testMachineList = deviceQrList3.join(', ');
				}) 
			},
			handleAddType() {
				this.show = true
			},
			// 新增故障类型
			addFaultType() {
				const req = {
					dictType: "testing_double_device",
					dictValue: this.faultForm.faultType,
					dictLabel: this.faultForm.faultType,
				};
				request({
					method: "POST",
					url: 'system/dict/data',
					data: req
				}).then((res) => {
					uni.showToast({
						title: '新增故障类型成功',
					});
					this.show = false
					this.getDoubleDevice()
				})
			},
			// 取消新增设备弹窗
			handleCancel() {
				this.show = false
			},
			// 存储图片
			checkImages(imageForms) {
				for (let dataElement of imageForms) {
					switch (dataElement.mediaType) {
						case "21": 
							if (dataElement.fileUrl !== null) {
								this.fileList1.push({
									type: "image",
									url: dataElement.fileUrl,
									status: "success",
									name: "",
									message: "",
									thumb: "",
									size: 60489
								})
							}
						default:
							continue;
					}
				}
			},
			// 流程
			demark(data) {
				this.historyList.push({
					id: 0,
					descTime: data.preArriveCustomerTime,
					title: '预计上门时间',
					istrue: !!data.preArriveCustomerTime && true
				}, {
					id: 1,
					descTime: data.pickOrderTime,
					title: '接单时间',
					istrue: !!data.pickOrderTime && true
				}, {
					id: 2,
					descTime: data.arriveCustomerTime,
					title: '上门时间',
					istrue: !!data.arriveCustomerTime && true
				}, {
					id: 3,
					descTime: data.startRecycleTime,
					title: '开始回收时间 ',
					istrue: !!data.startRecycleTime && true
				}, {
					id: 4,
					descTime: data.endRecycleTime,
					title: '结束回收时间',
					istrue: !!data.endRecycleTime && true
				})
			}
		},
		filters: {
			formatDate: function(value, args) {
				var dt = new Date(value);
				if (args == 'yyyy-M-d') { // yyyy-M-d
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					return `${year}-${month}-${date}`;
				} else if (args == 'yyyy-M-d H:m:s') { // yyyy-M-d H:m:s
					let year = dt.getFullYear();
					let month = dt.getMonth() + 1;
					let date = dt.getDate();
					let hour = dt.getHours();
					let minute = dt.getMinutes();
					let second = dt.getSeconds();
					return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
				} else if (args == 'yyyy-MM-dd') { // yyyy-MM-dd
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					return `${year}-${month}-${date}`;
				} else { // yyyy-MM-dd HH:mm:ss
					let year = dt.getFullYear();
					let month = (dt.getMonth() + 1).toString().padStart(2, '0');
					let date = dt.getDate().toString().padStart(2, '0');
					let hour = dt.getHours().toString().padStart(2, '0');
					let minute = dt.getMinutes().toString().padStart(2, '0');
					let second = dt.getSeconds().toString().padStart(2, '0');
					return `${month}-${date} ${hour}:${minute}`;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	._abbr {
		width: 100%;
		height: 100%;
		background-color: rgba(244, 249, 254, 1);

		.public {
			background-color: #ffffff;
			margin: 20upx;
			border-radius: 2%;
			padding: 20upx;
			border:1px solid;
			border-color:rgba(0, 124, 233, 0.4);
			.main_body_view {
				margin: 10upx;
			}
			.main_body_view_title {
				border-bottom: 1px solid black;
				margin-bottom: 10upx;
			}
			.device-fault {
				border: 1px solid #eee;
				.fault-item {
					display: flex;
					flex-flow: row wrap;
					align-content: flex-start;
					justify-content: flex-start;
					// justify-content: space-around;
					>view {
						box-sizing: border-box;
						flex: 0 0 33%;
						text-align: center;
					}
				}
			}
			.scan-item {
				margin: 10px 0;
				.input {
					margin: 10px 0 10px 6px;
					width: 100%;
				}
				.right-icon {
					position: relative;
					box-sizing: border-box;
					position: sticky;
					top: 0;
					z-index: 999;
					display: flex;
					overflow: hidden;
					justify-content: space-around;
					background: rgb(255, 255, 255);
					margin: 6px;
					.scan {
						position: absolute;
						top: 8upx;
						right: 14px;
					}
				}
				.test-scan {
					border: 1px solid #eee;
					padding: 8px;
				}
			}
			.button {
				display: flex;
			}
			.device {
				display: flex;
				justify-content: space-between;
				margin: 10px 0;
			}
			.device-item {
				display: flex;
				flex-direction: column;
			}
			.user_for {
				display: flex;
			}
			.line_for {
				width: 4rpx;
				height: 24rpx;
				margin: 0 20rpx 10rpx;
			}
			.line_radio {
				width: 20rpx;
				height: 20rpx;
				border-radius: 50%;
				position: relative;
				left: 50%;
				transform: translateX(-50%);
				top: 0;
			}
			.right_box {
				padding: 0rpx 20rpx 20rpx 20rpx;
			}
			.desc {
				font-size: 30rpx;
				display: flex;
				margin-top: 20rpx;
				align-items: center;
			}
		}
		.write {
			display: flex;
			justify-content: space-around;
			.im {
				width: 300rpx;
				image {
					width: 200rpx;
					height: 300rpx;
					position: relative;
					left: 30rpx;
				}
			}
		}
	}
</style>